﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Configuration;
using Newtonsoft.Json.Linq;


namespace QiangPiaoTool
{
    public partial class Form1 : Form
    {
         public Form1()
        {
            InitializeComponent();
        }
        //cookie容器
        CookieContainer _cc = new CookieContainer();
        //当前加载到的列车表
        // public List<Train> trainList = new List<Train>();
        public BindingList<Train> trainList = new BindingList<Train>();
        //乘车人
        List<Person> personList = new List<Person>();
        //选择的列车
        Train selectedTrain = new Train();
        //当前用户
        User user = new User();
        //乘车计划
        Plan plan = new Plan();
        //登陆验证码
        string loginRandCode = string.Empty;
        //提交验证码
        string submitRandCode = string.Empty;

        //是否已经登陆
        bool hasLogin = false;
        //登陆失败后是否重试
        bool isLoopLogin = false;
        //提交失败后是否重试
        bool isLoopSubmit = false;
        //窗体是否加载完成
        bool hasLoad = false;

        string leftTicketStr = string.Empty;
        string strutsToken = string.Empty;
        //随机数
        Random rnd = new Random();

        private void btnLogin_Click(object sender, EventArgs e)
        {
            //信息校验----------------------------------------------------
            if (string.IsNullOrEmpty(txtUid.Text) || string.IsNullOrEmpty(txtPwd.Text) || string.IsNullOrEmpty(txtLoginPassCode.Text))
            {
                ShowMsg("登陆信息填写不完整");
                return;
            }
            else if (string.IsNullOrEmpty(txtStartStation.Text) || string.IsNullOrEmpty(txtEndStation.Text))
            {
                ShowMsg("请填写登陆区间");
                return;
            }
            else if (personList == null || personList.Count == 0)
            {
                ShowMsg("请填写乘车人信息");
                return;
            }
            //----------------------------------------------------
            user.Name = txtUid.Text.Trim();
            user.Password = txtPwd.Text.Trim();
            loginRandCode = txtLoginPassCode.Text.Trim();

            ThreadPool.QueueUserWorkItem(new WaitCallback(_ =>
            {

                do
                {
                    if (Login())
                    {
                        hasLogin = true;
                        this.Invoke(new Action(() =>
                        {
                            btnQuery_Click(null, null);
                        }));
                    }
                    else
                    {
                        Thread.Sleep(rnd.Next(1000, 5000));
                    }
                }
                while (isLoopLogin && !hasLogin);

            }));

        }

        private void Form1_Load(object sender, EventArgs e)
        {

            ThreadPool.QueueUserWorkItem(new WaitCallback(_ =>
            {

                ShowMsg("正在初始化，请稍后……");
                //加载历史信息
                object objUser = Serializer.Deserialize(Application.StartupPath + "\\us.li");
                object objPerson = Serializer.Deserialize(Application.StartupPath + "\\per.li");
                object objPlan = Serializer.Deserialize(Application.StartupPath + "\\pla.li");

                user = (User)(objUser ?? new User());
                personList = (List<Person>)(objPerson ?? new List<Person>());
                plan = (Plan)(objPlan ?? new Plan());

                Sounds.Play("QiangPiaoTool.sta.wav");

                //显示到UI
                this.Invoke(new Action(() =>
                {
                    txtUid.Text = user.Name;
                    txtPwd.Text = user.Password;

                    txtStartStation.Text = plan.StartStation;
                    txtEndStation.Text = plan.EndStation;
                    if (!string.IsNullOrEmpty(plan.TrainDate))
                    {
                        dtpDate.Value = Convert.ToDateTime(plan.TrainDate);
                    }

                    dgvPersonList.AutoGenerateColumns = false;

                    bsPersonList.DataSource = personList;
                    bnPersonList.BindingSource = bsPersonList;
                    dgvPersonList.DataSource = bsPersonList;

                    //加载完成
                    hasLoad = true;

                }));
                //加载验证码
                loadLoginPassCode();
            }));


        }

        private void txtValiCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode.Equals(Keys.Enter))
            {
                loadLoginPassCode();
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            autoSelect();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!hasLogin)
            {
                ShowMsg("您还没登陆，请先登录");
                return;
            }
            else if (string.IsNullOrEmpty(txtSubmitPassCode.Text))
            {
                ShowMsg("你还没有填写验证码");
                return;
            }
            else if (selectedTrain == null || string.IsNullOrEmpty(selectedTrain.TrainCode))
            {
                ShowMsg("你还没有填写验证码");
                return;

            }
            //下面为了逻辑清晰，不再使用do while循环体
            submitRandCode = txtSubmitPassCode.Text.Trim();
            ThreadPool.QueueUserWorkItem(new WaitCallback(_ =>
            {

                //检查订单
                bool checkResult = checkOrderInfo();

                //2获取队列长度
                bool getCountResult = getQueueCount();

                //3提交订单
                bool confirmResult = confirmSingleForQueueOrder();

                while (isLoopSubmit && !confirmResult)
                {
                    //1检查订单
                    while (isLoopSubmit && !checkResult)
                    {
                        checkResult = checkOrderInfo();
                        Thread.Sleep(rnd.Next(1000, 5000));
                    }
                    //2获取队列长度
                    while (isLoopSubmit && !getCountResult)
                    {
                        getCountResult = getQueueCount();
                        Thread.Sleep(rnd.Next(1000, 5000));
                    }
                    //3提交订单
                    while (isLoopSubmit && !confirmResult)
                    {
                        confirmResult = confirmSingleForQueueOrder();
                        Thread.Sleep(rnd.Next(1000, 5000));
                    }
                }
                //检查预定结果
                if (confirmResult)
                {
                    bool checkRes = checkOrder();
                    while (!checkRes)
                    {
                        checkRes = checkOrder();
                        Thread.Sleep(rnd.Next(3000, 7000));
                    }
                    Sounds.Play("QiangPiaoTool.comp.wav");
                }

            }));
        }

        private void pbxLoginPassCode_Click(object sender, EventArgs e)
        {
            loadLoginPassCode();
        }

        private void pbxSumitPassCode_Click(object sender, EventArgs e)
        {
            loadSumitPassCode();
        }

        private void txtSubmitPassCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode.Equals(Keys.Enter))
            {
                loadSumitPassCode();
            }
        }

        private void dgvTrainList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1 && e.ColumnIndex > 5)
            {
                string cellText = dgvTrainList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (cellText.Contains("--") || cellText.Contains("无") || cellText.Contains("*"))
                {
                    return;
                }
                else if (personList.Count == 0)
                {
                    ShowMsg("你还没填乘车人信息");
                    return;
                }
                {

                    string seatTypeName = getSeatTypeByCombIndex(e.ColumnIndex - 6);

                    selectedTrain.TrainCode = dgvTrainList.Rows[e.RowIndex].Cells[0].Value.ToString().Trim();
                    string content = "您将要购买" + plan.TrainDate + plan.StartStation + "开往" + plan.EndStation + "" + "的" + selectedTrain.TrainCode + "次" + seatTypeName + "车票";
                    DialogResult result = MessageBox.Show(content, "确认订单信息", MessageBoxButtons.OKCancel);
                    if (result.ToString() == "OK")
                    {

                        selectedTrain = trainList.Where(i => i.TrainCode == selectedTrain.TrainCode).FirstOrDefault<Train>();
                        ThreadPool.QueueUserWorkItem(new WaitCallback(_ =>
                                          {
                                              bool requestResult = subOrderRequest();
                                              if (requestResult)
                                              {
                                                  //加载验证码
                                                  loadSumitPassCode();
                                              }
                                          }));
                    }
                }
            }
        }

        private void ckbLoginLoop_CheckedChanged(object sender, EventArgs e)
        {
            isLoopLogin = ckbLoginLoop.Checked;
        }

        private void ckbSubmitLoop_CheckedChanged(object sender, EventArgs e)
        {
            isLoopSubmit = ckbSubmitLoop.Checked;
        }

        private void dgvPersonList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                var curRow = dgvPersonList.Rows[e.RowIndex];
                if (curRow.Cells[0].Value != null && curRow.Cells[1].Value != null && curRow.Cells[2].Value != null)
                {
                    reLoadPersonList();
                }
            }
            catch
            {

            }
        }

        private void dgvPersonList_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            if (hasLoad)
            {
                reLoadPersonList();
            }
        }

        private void tmMonitor_Tick(object sender, EventArgs e)
        {
            autoSelect();
        }

        private void btnCancelMonitor_Click(object sender, EventArgs e)
        {
            groupBox2.Enabled = true;
            tmMonitor.Enabled = false;
            btnMonitor.Visible = false;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //保存用户信息
            User toSaveUser = null;
            if (ckbUserSave.Checked)
            {
                toSaveUser = user;
            }
            Serializer.Serialize(Application.StartupPath + "\\us.li", toSaveUser);

            //保存乘车计划
            Plan toSavePlan = null;

            if (ckbPlanSave.Checked)
            {
                toSavePlan = plan;
            }
            Serializer.Serialize(Application.StartupPath + "\\pla.li", toSavePlan);
        }

        private void btnMonitor_Click(object sender, EventArgs e)
        {
            groupBox2.Enabled = !groupBox2.Enabled;
            tmMonitor.Enabled = !tmMonitor.Enabled;

            if (btnMonitor.Text.Trim() == "自动监控")
            {
                btnMonitor.Text = "取消监控";
            }
            else
            {
                btnMonitor.Text = "自动监控";
            }
        }

    }
}
